#include <cstdio>
#include <cstring>

using namespace std;

const int maxn=110;
const int oo=100000000;

int g[maxn][maxn];
int n, m;
int app[maxn][maxn];
int a[maxn], b[maxn];
bool usex[maxn], usey[maxn];
int from[maxn];
int hh[maxn][2], mm[maxn][2];
int t1, t2;

bool can( int x ){
	usex[x]=true;
	for ( int i=0; i<n; i++ )
		if ( ! usey[i] && a[x]+b[i]==g[x][i] ){
			usey[i]=true;
			if ( from[i]==-1 || can( from[i] ) ){
				from[i]=x; return true;
			}
		}
	return false;
}

int abs( int x ){
	if ( x<0 ) return -x; else return x;
}

int km(){
	for ( int i=0; i<n; i++ )
		a[i]=-oo;
	memset( b, 0, sizeof( b ) );
	for ( int i=0; i<n; i++ )
		for ( int j=0; j<n; j++ ){
			g[i][j]=-g[i][j];
			if (g[i][j]>a[i])
				a[i]=g[i][j];
		}
	memset( from, -1, sizeof( from ) );
	int i=0, s=0, t;
	while ( true ){
		for ( t=i; t<n; t++ ){
			memset( usex, false, sizeof( usex ) );
			memset( usey, false, sizeof( usey ) );
			if ( can(t) ) s++; else break;
		}
		if ( s==n ){
			int ans=0;
			for ( int i=0; i<n; i++ )
				ans+=a[i]+b[i];
			return -ans;
		} else {
			int d=100000000;
			for ( int j=0; j<n; j++ )
				if ( usex[j] )
					for ( int k=0; k<n; k++ )
						if ( ! usey[k] && a[j]+b[k]-g[j][k]<d )
							d=a[j]+b[k]-g[j][k];
			for ( int j=0; j<=t; j++ )
				if ( usex[j] ) a[j]-=d;
			for ( int j=0; j<n; j++ )
				if ( usey[j] ) b[j]+=d;
			i=t;
		}
	}
}

int main(){
	while ( scanf("%d %d", &n, &m)==2 ){
		if ( n<=0 || m<=0 ) return 0;
		t1=0; t2=0;
		for ( int i=0; i<n; i++ )
			for ( int j=0; j<m; j++ ){
				char c;
				scanf(" %c", &c);
				if ( c=='H' ){
					hh[t1][0]=i; hh[t1][1]=j; t1++;
				}
				if ( c=='m' ){
					mm[t2][0]=i; mm[t2][1]=j; t2++;
				}
			}
		for ( int i=0; i<t1; i++ )
			for ( int j=0; j<t2; j++ )
				g[i][j]=abs( hh[i][0]-mm[j][0] )+abs( hh[i][1]-mm[j][1] );
		n=t1;
		printf("%d\n", km());
	}
}
